import { Button, message, Upload } from 'antd';
import { UploadOutlined } from '@ant-design/icons';
import React, { useState } from 'react';

const Uploader = (props) => {
  const { action, afterUpload, text, type, icon, accept } = props;
  const [files, setFiles] = useState([]);
  const [uploading, setUploading] = useState(false);

  const uploadProps = {
    name: 'file',
    action,
    accept,
    onChange: (info) => {
      if (info.file.status === 'uploading') {
        setUploading(true);
        setFiles(info.fileList);
      }
      if (info.file.status === 'done') {
        setFiles([]);
        message.success(`${info.file.name} 上传成功`);
        setUploading(false);
        afterUpload(info.files);
      } else if (info.file.status === 'error') {
        setFiles([]);
        setUploading(false);
        message.error(`${info.file.name} 上传失败.`);
      }
    },
  };
  const buttonProps = {
    icon: icon === undefined ? <UploadOutlined /> : icon,
  };

  return (
    <Upload key="upload" {...uploadProps} fileList={files} showUploadList={false}>
      <Button type={type || 'button'} {...buttonProps} loading={uploading}>
        {text || '上传文件'}
      </Button>
    </Upload>
  );
};

export default Uploader;
